package com.cslg.ac.demo.util.communicate;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CosClientUtil {

     private static final String appid = "1253457087";
     private static final String SecretId = "AKIDVor78shZXO1OWOaMSIsBE1YptkmYJKNA";
     private static final String SecretKey = "uZzB8qOhla9TYNvFJ8h28yax4xe7aKn3";
     private static final String region = "ap-guangzhou";


     public static String getBucket(int fileType){
         if(fileType == 0){
             return "image-1253457087";
         }
         if(fileType == 1){
             return "video-1253457087";
         }
         if(fileType == 2){
             return "album-1253457087";
         }
         if(fileType == 3){
             return "text-1253457087";
         }
         if(fileType == 4){
             return "photo-1253457087";
         }

        return null;
     }

    /**
     * 生成下载链接
     */
    public static String GenerateSimplePresignedDownloadUrl(String key,String buket) {
        COSCredentials cred = new BasicCOSCredentials(SecretId, SecretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);
        GeneratePresignedUrlRequest req =
                new GeneratePresignedUrlRequest(buket, key, HttpMethodName.GET);
        // 设置签名过期时间(可选), 若未进行设置则默认使用ClientConfig中的签名过期时间(5分钟)
        // 这里设置签名在半个小时后过期
        Date expirationDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
        req.setExpiration(expirationDate);
        URL url = cosclient.generatePresignedUrl(req);
        return url.toString();
    }



    public static void uploadFile(String key, int fileType, MultipartFile multipartFile){
        COSCredentials cred = new BasicCOSCredentials(SecretId,SecretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);
        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        TransferManager transferManager = new TransferManager(cosclient, threadPool);
        String fileName = multipartFile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        File tempFile = null;
        try {
            tempFile = File.createTempFile(key,prefix);
            multipartFile.transferTo(tempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(getBucket(fileType), key, tempFile);
        try {
            Upload upload = transferManager.upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(tempFile != null){
                tempFile.delete();
            }
            transferManager.shutdownNow();
            cosclient.shutdown();
        }
    }


    /**
     * 上传文本文件
     */
    public static void uploadTextStream(String stringToByte,String key,String bucket){
        COSCredentials cred = new BasicCOSCredentials(SecretId,SecretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);
        try {
            byte[] bytes1 = java.util.Base64.getDecoder().decode(stringToByte);
            InputStream bais = new ByteArrayInputStream(bytes1);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(bytes1.length);
            objectMetadata.setContentType("application/msword");
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucket, key, bais, objectMetadata);
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            String etag = putObjectResult.getETag();
        }catch (CosClientException e) {
            e.printStackTrace();
        }finally {
            cosclient.shutdown();
        }

    }


    /**
     * 上传视频流
     * @param stringToByte
     * @param key
     * @param buket
     */
    public static void uploadvideoStream(String stringToByte,String key,String buket){
        COSCredentials cred = new BasicCOSCredentials(SecretId,SecretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);
        try {
            byte[] bytes1 = java.util.Base64.getDecoder().decode(stringToByte);
            InputStream bais = new ByteArrayInputStream(bytes1);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(bytes1.length);
            objectMetadata.setContentType("video/x-ms-wmv");
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(buket, key, bais, objectMetadata);
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            String etag = putObjectResult.getETag();
        } catch (CosClientException e) {
            e.printStackTrace();
        }finally {
            cosclient.shutdown();
        }
    }


    /**
     * 上传图片流
     * @param key
     * @throws IOException
     */
    public static void uploadStream(String stringToByte,String key,String buket) {
// 指定要上传到 COS 上的路径
//        String key = "/test121.jpg";
        COSCredentials cred = new BasicCOSCredentials(SecretId,SecretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);
        try {
            byte[] bytes1 = java.util.Base64.getDecoder().decode(stringToByte);
            InputStream bais = new ByteArrayInputStream(bytes1);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
            objectMetadata.setContentLength(bytes1.length);
            // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
            objectMetadata.setContentType("image/jpeg");
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(buket, key, bais, objectMetadata);
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia), 近线(nearline)
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
        } catch (CosClientException e) {
            e.printStackTrace();
        }finally {
            cosclient.shutdown();
        }
    }

    public static void deleteFile(String key,String buket){
        COSCredentials cred = new BasicCOSCredentials(SecretId,SecretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);
        cosclient.deleteObject(buket, key);
        cosclient.shutdown();
    }






}
